/*
 * =====================================================================================
 *
 *       Filename:  remove.c
 *
 *    Description:  remove a directory or a file
 *
 *        Version:  1.0
 *        Created:  Friday 21 September 2012 09:16:13  IST
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include "../include/test.h"
#include "../include/Hash.h"
#include "../include/bst.h"
#include "../include/linked_block.h"
	int removeNode(int file_descriptor_no){
		int i=0,parent_file_descriptor_no=0;
		struct Node *node,*parentNode,*temp,*prev;
		node = searchNode(file_descriptor_no);
		if(node->child==NULL){
		parent_file_descriptor_no = header.fd[file_descriptor_no].parent_file_descriptor_no;
		parentNode = searchNode(parent_file_descriptor_no);
		if(parentNode->child == node)
{
			// If the node to be removed is directly parent's child the we are updating the parent's direct child to the removed node's sibling
			parentNode->child = node->sibling;
			temp=node;
}		else{
			// Traversing the cildren of parent node in ordr to update the pointers of previous node of the node to be removed to the removed node's sibling
			temp = parentNode->child;
			while(temp->file_descriptor_no < file_descriptor_no){
				prev = temp;
				temp = temp->sibling;
				
			}
			prev->sibling = temp->sibling;
		}
		//removeTraverse(node->child);
                
                delete_from_hash_table(header.fd[file_descriptor_no].path,file_descriptor_no);     
                header.fd[file_descriptor_no].used_flag=0;
                if(header.fd[file_descriptor_no].file_type=='f')
		{
                   header.free_blocks[header.fd[file_descriptor_no].location_block_number]=0;      
		   bst=delete_bst(header.fd[file_descriptor_no].file_name,bst,file_descriptor_no);
                 
		   //Add the block back to the list-will call later
		   //add_free_block(header.fd[file_descriptor_no].location_block_number);		
		}
               

		free(temp);	
		}else{
		//printf("ERROR!!!");
			return -1;
		}
		return 0;
	}

	/*void removeTraverse(struct Node* node){
		if(node == NULL)
			return;
		removeTraverse(node->child);
		removeTraverse(node->sibling);
		//printf("Deleting file %s",header.fd[node->file_descriptor_no].file_name);
		


               delete_from_hash_table(header.fd[node->file_descriptor_no].path,node->file_descriptor_no);     
                header.fd[node->file_descriptor_no].used_flag=0;
                if(header.fd[node->file_descriptor_no].file_type=='f')
		{
                   header.free_blocks[header.fd[node->file_descriptor_no].location_block_number]=0;				
		   bst=delete_bst(header.fd[node->file_descriptor_no].file_name,bst,node->file_descriptor_no);	
		}
		free(node);
	}*/

